/*
 * CamDemo.cpp
 *
 *  Created on: 10 Nov 2012
 *      Author: hopey
 */

#include "CamDemo.h"
#include <iostream>
#include "gui/FilterListView.h"
using namespace Gtk;

namespace openlid {
const int w = 320, h = 240;

CamDemo::CamDemo(int argc, char** argv) :
		OpenLidDemo(argc, argv), beforeWidget(Mat(w, h, CV_8UC3, Scalar(255, 255, 255)))

{

	//This is ugly, my stupid old webcam dies sometimes. If I need to use 2, I'll make it tidier.
	webcam.open(0);
	if (!webcam.isOpened()) {
		cerr << "Couldn't open webcam 0, let's try 1!" << endl;
		webcam.open(1);
		if (!webcam.isOpened()) {
			cerr << "Couldn't open webcam 1 either, goodnight!" << endl;
			//?
			exit(1);
		}
	}


//	filterChain.add_filter(new GrayScaleFilter());
//	filterChain.add_filter(new BlurFilter(3));
//	filterChain.add_filter(new FourierTransformFilter(true));
//
//	filterChain2.add_filter(new GrayScaleFilter());
//	filterChain2.add_filter(new FourierTransformFilter(true));

}

CamDemo::~CamDemo() {
	// TODO Auto-generated destructor stub
}

unique_ptr<Window> CamDemo::create_components() {
	Window* win = new Window();
	win->set_title("Cam Demo");
	win->set_default_size(w, h * 2); //Plus border?

	auto box = retain(new VBox);
	box->pack_start(beforeWidget);
	box->pack_end(afterWidget);
//	box->pack_end(spareWidget);
	win->add(*box);
	win->show_all_children();

	auto win2 = retain(new Window());
	win2->set_title("Hi there!");
	//win2->add(spareWidget);

	auto flv = retain(new FilterListView);
	filterChain = shared_ptr<FilterChain>(flv->getFilterChain());
	win2->add(*flv);
	win2->show();
	win2->show_all_children();

	timerConnection = Glib::signal_timeout().connect(sigc::mem_fun(*this, &CamDemo::timer_callback), 1000 / FRAMERATE);

	return unique_ptr<Window>(win);
}

bool CamDemo::timer_callback() {
	cout << "." << flush;
	webcam >> beforeMat;
	afterMat = filterChain->apply(beforeMat);
	//spareMat = filterChain2.apply(beforeMat);

	beforeWidget.set_mat(beforeMat);
	afterWidget.set_mat(afterMat);
	spareWidget.set_mat(spareMat);

	return true;
}

} /* namespace openlid */

int main(int argc, char** argv) {
	openlid::CamDemo demo(argc, argv);
	demo.start();
	return 0;
}
